package xyz.luhui1hao.sell.controller;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xyz.luhui1hao.sell.domain.ProductCategory;
import xyz.luhui1hao.sell.domain.ProductInfo;
import xyz.luhui1hao.sell.vo.ProductInfoVO;
import xyz.luhui1hao.sell.vo.ProductVO;
import xyz.luhui1hao.sell.vo.ResultVO;
import xyz.luhui1hao.sell.service.CategoryService;
import xyz.luhui1hao.sell.service.ProductInfoService;
import xyz.luhui1hao.sell.utils.ResultVOUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName BuyerProductController
 * @Description 买家商品
 * @Author luhui1hao
 * @Date 2018/8/20 下午2:15
 * @Version 1.0
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public ResultVO list(){
        //1.查询所有的上架商品
        List<ProductInfo> productInfoList = productInfoService.findUpAll();

        //2.查询类目(一次性查询)
        List<Integer> categoryIds = new ArrayList<>();

        for (ProductInfo productInfo : productInfoList) {
            categoryIds.add(productInfo.getCategoryType());
        }

        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryIds);


        //3.数据拼装
        List<ProductVO> productVOList = new ArrayList<>();
        for(ProductCategory productCategory : productCategoryList){
            ProductVO productVO = new ProductVO();
            productVO.setCategoryType(productCategory.getCategoryType());
            productVO.setCategoryName(productCategory.getCategoryName());

            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            for(ProductInfo productInfo : productInfoList){
                if(productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo, productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }

        return ResultVOUtil.success(productVOList);
    }

}
